import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class QuestionEditDialog extends JDialog {
    private Question question;
    private Question resultQuestion;
    private int questionOrder;

    // UI组件
    private JComboBox<String> typeComboBox;
    private JTextArea questionTextArea;
    private JTextField scoreField;
    private JPanel optionsPanel;
    private JPanel trueFalsePanel; // 新增：判断题面板
    private JRadioButton trueRadio, falseRadio; // 新增：判断题选项
    private JTextField correctAnswerField; // 新增：填空题正确答案
    private List<OptionPanel> optionPanels = new ArrayList<>();
    private JButton addOptionButton;
    private JButton removeOptionButton;
    private JButton saveButton;
    private JButton cancelButton;

    public QuestionEditDialog(JFrame parent, Question question, int questionOrder) {
        super(parent, question == null ? "添加题目" : "编辑题目", true);
        this.question = question;
        this.questionOrder = questionOrder;

        initComponents();
        setupLayout();
        setupEvents();

        if (question != null) {
            loadQuestionData();
        } else {
            // 默认添加4个选项
            addOption();
            addOption();
            addOption();
            addOption();
        }

        updateOptionsVisibility();
    }

    private void initComponents() {
        setSize(1000, 800); // 增大对话框尺寸
        setLocationRelativeTo(getParent());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setResizable(true);

        // 字体设置
        Font labelFont = new Font("微软雅黑", Font.BOLD, 18);
        Font fieldFont = new Font("微软雅黑", Font.PLAIN, 16);

        // 题目类型下拉框 - 添加判断题
        String[] types = { "single_choice", "multiple_choice", "true_false", "fill_blank", "essay" };
        typeComboBox = new JComboBox<>(types);
        typeComboBox.setFont(fieldFont);
        typeComboBox.setPreferredSize(new Dimension(200, 45));
        typeComboBox.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
                    boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value != null) {
                    setText(getQuestionTypeText(value.toString()));
                }
                return this;
            }
        });

        // 题目内容文本区域 - 显著增大
        questionTextArea = new JTextArea(10, 60);
        questionTextArea.setFont(fieldFont);
        questionTextArea.setLineWrap(true);
        questionTextArea.setWrapStyleWord(true);
        questionTextArea.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)));

        // 分值输入框 - 显著增大并美化
        scoreField = new JTextField("5");
        scoreField.setFont(new Font("微软雅黑", Font.BOLD, 20));
        scoreField.setPreferredSize(new Dimension(120, 50));
        scoreField.setHorizontalAlignment(JTextField.CENTER);
        scoreField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                BorderFactory.createEmptyBorder(10, 15, 10, 15)));

        // 选项面板
        optionsPanel = new JPanel();
        optionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.Y_AXIS));
        optionsPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(40, 167, 69), 2),
                "选项设置",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                labelFont,
                new Color(40, 167, 69)));

        // 新增：判断题面板
        trueFalsePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 10));
        trueFalsePanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(255, 193, 7), 2),
                "正确答案",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                labelFont,
                new Color(255, 193, 7)));

        trueRadio = new JRadioButton("正确 (True)", true);
        falseRadio = new JRadioButton("错误 (False)");
        trueRadio.setFont(fieldFont);
        falseRadio.setFont(fieldFont);

        ButtonGroup trueFalseGroup = new ButtonGroup();
        trueFalseGroup.add(trueRadio);
        trueFalseGroup.add(falseRadio);

        trueFalsePanel.add(trueRadio);
        trueFalsePanel.add(falseRadio);

        // 新增：填空题正确答案输入框
        correctAnswerField = new JTextField();
        correctAnswerField.setFont(fieldFont);
        correctAnswerField.setPreferredSize(new Dimension(600, 45));
        correctAnswerField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                BorderFactory.createEmptyBorder(10, 15, 10, 15)));

        // 按钮
        Dimension buttonSize = new Dimension(120, 45);

        addOptionButton = new JButton("添加选项");
        addOptionButton.setFont(labelFont);
        addOptionButton.setPreferredSize(buttonSize);
        addOptionButton.setBackground(new Color(40, 167, 69));
        addOptionButton.setForeground(Color.WHITE);
        addOptionButton.setBorder(BorderFactory.createEmptyBorder());
        addOptionButton.setFocusPainted(false);

        removeOptionButton = new JButton("删除选项");
        removeOptionButton.setFont(labelFont);
        removeOptionButton.setPreferredSize(buttonSize);
        removeOptionButton.setBackground(new Color(220, 53, 69));
        removeOptionButton.setForeground(Color.WHITE);
        removeOptionButton.setBorder(BorderFactory.createEmptyBorder());
        removeOptionButton.setFocusPainted(false);

        saveButton = new JButton("保存");
        saveButton.setFont(new Font("微软雅黑", Font.BOLD, 18));
        saveButton.setPreferredSize(new Dimension(100, 50));
        saveButton.setBackground(new Color(70, 130, 180));
        saveButton.setForeground(Color.WHITE);
        saveButton.setBorder(BorderFactory.createEmptyBorder());
        saveButton.setFocusPainted(false);

        cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("微软雅黑", Font.BOLD, 18));
        cancelButton.setPreferredSize(new Dimension(100, 50));
        cancelButton.setBackground(new Color(108, 117, 125));
        cancelButton.setForeground(Color.WHITE);
        cancelButton.setBorder(BorderFactory.createEmptyBorder());
        cancelButton.setFocusPainted(false);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));

        // 顶部标题面板
        JPanel topPanel = new JPanel();
        topPanel.setBackground(new Color(70, 130, 180));
        topPanel.setPreferredSize(new Dimension(1000, 80));
        JLabel titleLabel = new JLabel(question == null ? "添加题目" : "编辑题目", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 26));
        titleLabel.setForeground(Color.WHITE);
        topPanel.add(titleLabel);

        // 主要内容面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 基本信息面板
        JPanel basicInfoPanel = createBasicInfoPanel();

        // 题目内容面板
        JPanel contentPanel = createContentPanel();

        // 选项设置面板
        JPanel optionContainer = createOptionPanel();

        mainPanel.add(basicInfoPanel);
        mainPanel.add(Box.createVerticalStrut(15));
        mainPanel.add(contentPanel);
        mainPanel.add(Box.createVerticalStrut(15));
        mainPanel.add(optionContainer);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 20));
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        add(topPanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private JPanel createBasicInfoPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 15));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "基本信息",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(70, 130, 180)));

        Font labelFont = new Font("微软雅黑", Font.BOLD, 18);

        JLabel typeLabel = new JLabel("题目类型:");
        typeLabel.setFont(labelFont);
        typeLabel.setForeground(new Color(70, 130, 180));
        panel.add(typeLabel);
        panel.add(typeComboBox);

        // 添加一些间距
        panel.add(Box.createHorizontalStrut(40));

        JLabel scoreLabel = new JLabel("分值:");
        scoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        scoreLabel.setForeground(new Color(70, 130, 180));
        panel.add(scoreLabel);
        panel.add(scoreField);

        return panel;
    }

    private JPanel createContentPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "题目内容",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(70, 130, 180)));

        JScrollPane questionScrollPane = new JScrollPane(questionTextArea);
        questionScrollPane.setPreferredSize(new Dimension(900, 220));
        questionScrollPane.setBorder(BorderFactory.createLineBorder(new Color(70, 130, 180), 2));

        panel.add(questionScrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createOptionPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(70, 130, 180), 2),
                "选项设置",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(70, 130, 180)));

        // 创建一个容器面板，包含所有类型的答案设置
        JPanel answerContainer = new JPanel();
        answerContainer.setLayout(new BoxLayout(answerContainer, BoxLayout.Y_AXIS));

        // 选择题选项面板
        JScrollPane optionsScrollPane = new JScrollPane(optionsPanel);
        optionsScrollPane.setPreferredSize(new Dimension(900, 250));
        optionsScrollPane.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        answerContainer.add(optionsScrollPane);

        // 判断题面板
        answerContainer.add(trueFalsePanel);

        // 填空题正确答案面板
        JPanel fillBlankPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 10));
        fillBlankPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(255, 193, 7), 2),
                "正确答案",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("微软雅黑", Font.BOLD, 18),
                new Color(255, 193, 7)));

        JLabel answerLabel = new JLabel("标准答案：");
        answerLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        answerLabel.setForeground(new Color(255, 193, 7));
        fillBlankPanel.add(answerLabel);
        fillBlankPanel.add(correctAnswerField);

        answerContainer.add(fillBlankPanel);

        panel.add(answerContainer, BorderLayout.CENTER);

        // 选择题按钮面板
        JPanel optionButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 20, 15));
        optionButtonPanel.add(addOptionButton);
        optionButtonPanel.add(removeOptionButton);
        panel.add(optionButtonPanel, BorderLayout.SOUTH);

        return panel;
    }

    private void setupEvents() {
        typeComboBox.addActionListener(e -> updateOptionsVisibility());

        addOptionButton.addActionListener(e -> {
            addOption();
            updateOptionsVisibility();
        });

        removeOptionButton.addActionListener(e -> {
            if (!optionPanels.isEmpty()) {
                OptionPanel lastPanel = optionPanels.get(optionPanels.size() - 1);
                optionsPanel.remove(lastPanel);
                optionPanels.remove(lastPanel);
                optionsPanel.revalidate();
                optionsPanel.repaint();
            }
        });

        saveButton.addActionListener(e -> saveQuestion());
        cancelButton.addActionListener(e -> dispose());
    }

    private void addOption() {
        char label = (char) ('A' + optionPanels.size());
        OptionPanel optionPanel = new OptionPanel(String.valueOf(label));
        optionPanels.add(optionPanel);
        optionsPanel.add(optionPanel);
        optionsPanel.revalidate();
        optionsPanel.repaint();
    }

    private void updateOptionsVisibility() {
        String selectedType = (String) typeComboBox.getSelectedItem();
        boolean showOptions = "single_choice".equals(selectedType) || "multiple_choice".equals(selectedType);
        boolean showTrueFalse = "true_false".equals(selectedType);
        boolean showCorrectAnswer = "fill_blank".equals(selectedType);

        // 控制选择题选项显示
        for (OptionPanel panel : optionPanels) {
            panel.setVisible(showOptions);
        }

        // 控制按钮显示
        addOptionButton.setVisible(showOptions);
        removeOptionButton.setVisible(showOptions);

        // 控制判断题面板显示
        trueFalsePanel.setVisible(showTrueFalse);

        // 控制填空题正确答案面板显示
        Component fillBlankPanel = null;
        Container parent = correctAnswerField.getParent();
        if (parent != null) {
            fillBlankPanel = parent;
            fillBlankPanel.setVisible(showCorrectAnswer);
        }

        // 重新验证和重绘
        if (optionsPanel.getParent() != null) {
            optionsPanel.getParent().revalidate();
            optionsPanel.getParent().repaint();
        }

        // 重新验证整个对话框
        revalidate();
        repaint();
    }

    private void loadQuestionData() {
        typeComboBox.setSelectedItem(question.getQuestionType());
        questionTextArea.setText(question.getQuestionText());
        scoreField.setText(String.valueOf(question.getScore()));

        // 加载正确答案（判断题和填空题）
        if (question.getCorrectAnswer() != null) {
            if (question.isTrueFalseQuestion()) {
                if ("true".equals(question.getCorrectAnswer())) {
                    trueRadio.setSelected(true);
                } else {
                    falseRadio.setSelected(true);
                }
            } else if (question.isFillBlankQuestion()) {
                correctAnswerField.setText(question.getCorrectAnswer());
            }
        }

        if (question.getOptions() != null && !question.getOptions().isEmpty()) {
            // 清除默认选项
            optionPanels.clear();
            optionsPanel.removeAll();

            // 加载现有选项
            for (QuestionOption option : question.getOptions()) {
                OptionPanel optionPanel = new OptionPanel(option.getOptionLabel());
                optionPanel.setOptionText(option.getOptionText());
                optionPanel.setCorrect(option.isCorrect());
                optionPanels.add(optionPanel);
                optionsPanel.add(optionPanel);
            }
        }
    }

    private void saveQuestion() {
        if (!validateInput()) {
            return;
        }

        resultQuestion = new Question();
        resultQuestion.setQuestionType((String) typeComboBox.getSelectedItem());
        resultQuestion.setQuestionText(questionTextArea.getText().trim());
        resultQuestion.setQuestionOrder(questionOrder);
        resultQuestion.setScore(Double.parseDouble(scoreField.getText()));

        // 设置正确答案
        String questionType = resultQuestion.getQuestionType();
        if ("true_false".equals(questionType)) {
            resultQuestion.setCorrectAnswer(trueRadio.isSelected() ? "true" : "false");
        } else if ("fill_blank".equals(questionType)) {
            resultQuestion.setCorrectAnswer(correctAnswerField.getText().trim());
        }

        // 如果是选择题，保存选项
        if (resultQuestion.isChoiceQuestion()) {
            List<QuestionOption> options = new ArrayList<>();
            for (OptionPanel panel : optionPanels) {
                if (panel.isVisible() && !panel.getOptionText().trim().isEmpty()) {
                    QuestionOption option = new QuestionOption();
                    option.setOptionLabel(panel.getLabel());
                    option.setOptionText(panel.getOptionText());
                    option.setCorrect(panel.isCorrect());
                    options.add(option);
                }
            }
            resultQuestion.setOptions(options);
        }

        dispose();
    }

    private boolean validateInput() {
        if (questionTextArea.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入题目内容！", "验证失败", JOptionPane.WARNING_MESSAGE);
            return false;
        }

        try {
            double score = Double.parseDouble(scoreField.getText());
            if (score <= 0) {
                JOptionPane.showMessageDialog(this, "分值必须大于0！", "验证失败", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "分值必须是数字！", "验证失败", JOptionPane.WARNING_MESSAGE);
            return false;
        }

        String selectedType = (String) typeComboBox.getSelectedItem();

        // 验证填空题正确答案
        if ("fill_blank".equals(selectedType)) {
            if (correctAnswerField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请输入填空题的正确答案！", "验证失败", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        }

        // 验证选择题选项
        if ("single_choice".equals(selectedType) || "multiple_choice".equals(selectedType)) {
            // 检查选项
            int validOptions = 0;
            int correctOptions = 0;

            for (OptionPanel panel : optionPanels) {
                if (panel.isVisible() && !panel.getOptionText().trim().isEmpty()) {
                    validOptions++;
                    if (panel.isCorrect()) {
                        correctOptions++;
                    }
                }
            }

            if (validOptions < 2) {
                JOptionPane.showMessageDialog(this, "选择题至少需要2个选项！", "验证失败", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (correctOptions == 0) {
                JOptionPane.showMessageDialog(this, "请至少设置一个正确答案！", "验证失败", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if ("single_choice".equals(selectedType) && correctOptions > 1) {
                JOptionPane.showMessageDialog(this, "单选题只能有一个正确答案！", "验证失败", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        }

        return true;
    }

    public Question getQuestion() {
        return resultQuestion;
    }

    private String getQuestionTypeText(String type) {
        switch (type) {
            case "single_choice":
                return "单选题";
            case "multiple_choice":
                return "多选题";
            case "true_false":
                return "判断题";
            case "fill_blank":
                return "填空题";
            case "essay":
                return "问答题";
            default:
                return type;
        }
    }

    // 选项面板内部类
    private class OptionPanel extends JPanel {
        private String label;
        private JTextField textField;
        private JCheckBox correctCheckBox;

        public OptionPanel(String label) {
            this.label = label;
            setLayout(new BorderLayout(15, 10));
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(Color.LIGHT_GRAY),
                    BorderFactory.createEmptyBorder(12, 15, 12, 15)));
            setMaximumSize(new Dimension(Integer.MAX_VALUE, 60));

            JLabel labelComponent = new JLabel(label + ".");
            labelComponent.setFont(new Font("微软雅黑", Font.BOLD, 18));
            labelComponent.setPreferredSize(new Dimension(40, 45));
            labelComponent.setForeground(new Color(70, 130, 180));

            textField = new JTextField();
            textField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
            textField.setPreferredSize(new Dimension(600, 45));
            textField.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(Color.GRAY),
                    BorderFactory.createEmptyBorder(5, 10, 5, 10)));

            correctCheckBox = new JCheckBox("正确答案");
            correctCheckBox.setFont(new Font("微软雅黑", Font.BOLD, 16));
            correctCheckBox.setForeground(new Color(40, 167, 69));

            add(labelComponent, BorderLayout.WEST);
            add(textField, BorderLayout.CENTER);
            add(correctCheckBox, BorderLayout.EAST);
        }

        public String getLabel() {
            return label;
        }

        public String getOptionText() {
            return textField.getText();
        }

        public void setOptionText(String text) {
            textField.setText(text);
        }

        public boolean isCorrect() {
            return correctCheckBox.isSelected();
        }

        public void setCorrect(boolean correct) {
            correctCheckBox.setSelected(correct);
        }
    }
}